package com.ddh.codeduck.infra.websocket.intercetor;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.text.CharSequenceUtil;

import com.ddhcodeduck.common.exception.BusinessException;
import com.ddhcodeduck.common.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
@Slf4j
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {

    /**
     * 握手前执行
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //从请求头解析token
        String token = request.getHeaders().getFirst("Authorization");

        if (token == null || token.isEmpty()) {
            log.info("缺少 token，拒绝连接");
            throw new BusinessException(ErrorCode.TOKEN_MISSING_ERROR);
        }

        // 2. 解析 token 获取用户名
        String userId = StpUtil.getLoginIdAsString();

        if (CharSequenceUtil.isEmpty(userId)) {
            log.info("无效token，拒绝连接");
            throw new BusinessException(ErrorCode.TOKEN_INVALID_ERROR);
        }

        // 3. 将用户名存入 attributes，供后续处理器使用
        attributes.put("userId", userId);
        return true;
    }

    /**
     * 握手成功后执行
     * @param request
     * @param response
     * @param wsHandler
     * @param exception
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {
        // 握手完成后可选操作
        log.info("WebSocket 握手完成");
    }
}
